package com.effects.cd
{
	import com.effects.CDEffect;
	import com.ui.manager.UIManager;

	import flash.events.Event;
	import flash.utils.Dictionary;
	import flash.utils.getTimer;

	/**
	 * @author Cafe
	 */
	public class CDManage
	{
		private static var _instance:CDManage;
		private static var _list:Dictionary = new Dictionary();
		private static var _cdList:Vector.<CDData> = new Vector.<CDData>();
		private var runing:Boolean;

		public static function get instance():CDManage
		{
			if (_instance == null) _instance = new CDManage();
			return _instance;
		}

		public function add( value:CDEffect ):void
		{
			if (_list[value.cdID] == null) _list[value.cdID] = new Array();
			_list[value.cdID].push( value );
		}

		public function remove( cd:CDEffect ):void
		{
			var data:Array = _list[cd.cdID];
			if (data == null) return;
			for (var i:int = 0; i < data.length; i ++)
			{
				if (data[i] == cd) data.splice( data.indexOf( cd ) , 1 );
			}
		}

		public function getCDTime( cdID:uint ):uint
		{
			for (var i:int = 0; i < _cdList.length; i ++)
			{
				if (_cdList[i] && _cdList[i].cdID == cdID)
					return _cdList[i].startTime + _cdList[i].cdTime - getTimer();
			}
			return 0;
		}

		public function startCD( cdID:uint , time:uint ):void
		{
			if (time == 0) return;
			var cdData:CDData = new CDData();
			cdData.cdList = _list[cdID];
			cdData.cdID = cdID;
			cdData.startTime = getTimer();
			cdData.cdTime = time;
			_cdList.push( cdData );
			if (runing == false)
			{
				UIManager.root.addEventListener( Event.ENTER_FRAME , frame_handler );
				runing = true;
			}
		}

		public function stopCD( cdID:uint ):void
		{
			for (var i:int = 0; i < _cdList.length; i ++)
			{
				if (_cdList[i])
					if (_cdList[i].cdID == cdID)
					{
						_cdList[i].clear();
						_cdList.splice( i , 1 );
						i = 0;
					}
			}
		}

		public function reStartCD( cdID:uint , time:uint , cdTime:uint ):void
		{
			if (time == 0) return;
			var cdData:CDData = new CDData();
			cdData.cdList = _list[cdID];
			cdData.startTime = getTimer();
			cdData.oldTime = cdTime - time ;
			cdData.cdTime = cdTime;
			cdData.cdID = cdID;
			_cdList.push( cdData );
			if (runing == false)
			{
				UIManager.root.addEventListener( Event.ENTER_FRAME , frame_handler );
				runing = true;
			}
		}

		private function frame_handler( event:Event ):void
		{
			var time:int = getTimer();

			for each (var i : CDData in _cdList)
			{
				if (i.end || i.cdList == null)
				{
					_cdList.splice( _cdList.indexOf( i ) , 1 );
					continue;
				}
				i.cd( time );
			}

			if (_cdList.length == 0)
			{
				UIManager.root.removeEventListener( Event.ENTER_FRAME , frame_handler );
				runing = false;
			}
		}
	}
}
